package com.yk.govpro.service.request.impl;

import com.yk.govpro.service.request.api.IJSONRequestService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * Created by zsyoung on 2017/5/19.
 */
@Service("jsonRequestService")
public class JSONRequsetServiceImpl implements IJSONRequestService {
    @Override
    public JSONArray requestJSONArray(URL url) {
        return null;
    }

    @Override
    public JSONObject requestJSONObject(URL url) {
        StringBuilder builder = new StringBuilder();
        BufferedReader bufferedReader=null;

        try {
        InputStream inputStream = url.openStream();
        bufferedReader=new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            while (bufferedReader.ready()){
                builder.append(bufferedReader.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return new JSONObject((builder.toString()));
        }
    }


}
